package com.zp.manager.auth;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zp.domain.entity.Space;
import com.zp.domain.entity.SpaceUser;
import com.zp.domain.entity.User;
import com.zp.enums.SpaceTypeEnum;
import com.zp.enums.SpaceUserRoleEnum;
import com.zp.manager.auth.model.SpaceUserAuthConfig;
import com.zp.manager.auth.model.SpaceUserRole;
import com.zp.service.SpaceUserService;
import com.zp.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Component
public class SpaceUserAuthManager {
    @Resource
    private UserService userService;
    @Resource
    private SpaceUserService spaceUserService;

    private static final SpaceUserAuthConfig SPACE_USER_AUTH_CONFIG;

    static {
        String json = ResourceUtil.readUtf8Str("biz/spaceUserAuthConfig.json");
        SPACE_USER_AUTH_CONFIG = JSONUtil.toBean(json, SpaceUserAuthConfig.class);
    }

    /**
     * 根据角色获取权限
     * @param spaceUserRole viewer/editor/admin
     * @return 权限列表
     */
    public List<String> getPermissionsByRole(String spaceUserRole) {
        if (StrUtil.isBlank(spaceUserRole)) {
            return Collections.emptyList();
        }
        SpaceUserRole role = SPACE_USER_AUTH_CONFIG.getRoles().stream()
                .filter(userRole -> userRole.getKey().equals(spaceUserRole))
                .findFirst()
                .orElse(null);
        return role == null ? Collections.emptyList() : role.getPermissions();
    }

    /**
     * 获取当前登录用户在某空间的权限列表
     */
    public List<String> getPermissionList(Space space, User loginUser) {
        if (loginUser == null) {
            return Collections.emptyList();
        }
        List<String> ADMIN_PERMISSIONS = this.getPermissionsByRole(SpaceUserRoleEnum.ADMIN.getValue());
        // 全局管理员在任何空间均拥有全部权限（包含团队空间）
        if (userService.isAdmin(loginUser)) {
            return ADMIN_PERMISSIONS;
        }
        if (space == null) {
            // 公共仓库：非管理员无权限
            return Collections.emptyList();
        }
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(space.getSpaceType());
        if (spaceTypeEnum == null) {
            return Collections.emptyList();
        }
        switch (spaceTypeEnum) {
            case PRIVATE:
                // 私有空间：本人有权限
                if (loginUser.getId().equals(space.getUserId())) {
                    return ADMIN_PERMISSIONS;
                } else {
                    return Collections.emptyList();
                }
            case TEAM:
                // 团队空间：查询成员角色并返回对应权限
                SpaceUser spaceUser = spaceUserService.lambdaQuery()
                        .eq(SpaceUser::getSpaceId, space.getId())
                        .eq(SpaceUser::getUserId, loginUser.getId())
                        .one();
                if (spaceUser == null) {
                    return Collections.emptyList();
                } else {
                    return this.getPermissionsByRole(spaceUser.getSpaceRole());
                }
            default:
                return Collections.emptyList();
        }
    }
}
